
from . import profile_blue
from flask import render_template,g,redirect,request,jsonify,current_app,session
from info.utils.commons import login_required
from info.utils.response_code import RET
from info import db
from info.utils.image_storage import storage
from info.constants import QINIU_DOMIN_PREFIX
from info.models import Category,News


@profile_blue.route('/info')
@login_required
def user_info():
    user=g.user
    if not user:
        return redirect('/')
    data={
        'user':user.to_dict()
    }
    return render_template('news/user.html',data=data)



@profile_blue.route('/base_info',methods=['GET','POST'])
@login_required
def base_info():
    # 查看用户是否登陆，没登陆就重定向到主页
    user=g.user
    # 如果是get请求就返回模板数据
    if request.method=='GET':
        data={
            'user':user.to_dict()
        }
        return render_template('news/user_base_info.html',data=data)
    # 如果是post请求就获取参数
    nick_name=request.json.get('nick_name')
    signature=request.json.get('signature')
    gender=request.json.get('gender')
    if not all ([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    if gender not in ('MAN', 'WOMAN'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数格式错误')
    user.nick_name=nick_name,
    user.signature=signature,
    user.gender=gender
    try:
        db.session.add(user),
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')

    session['nick_name']=nick_name
    return jsonify(errno=RET.OK,errmsg='成功')
    pass

@profile_blue.route('/pic_info',methods=['GET','POST'])
@login_required
def pic_info():
    user=g.user
    if not user:
        return redirect('/')
    if request.method=='GET':
        return render_template('news/user_pic_info.html')
    avatar=request.files.get('avatar')
    try:
        image=avatar.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='读取图片文件失败')
    try:
        url=storage(image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='上传图片失败')
    user.avatar_url=url
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='上传图片到数据库失败')

    return jsonify(errno=RET.OK,errmsg='OK',data=QINIU_DOMIN_PREFIX+url)
    pass
# 修改密码
@profile_blue.route('/pass_info',methods=['GET','POST'])
@login_required
def pass_info():
    if request.method=='GET':
        return render_template('news/user_pass_info.html')
    old_password=request.json.get('old_password')
    new_password=request.json.get('new_password')
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    user=g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR,errmsg='旧密码不正确')
    user.password=new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='密码提交数据库失败')
    return jsonify(errno=RET.OK,errmsg='OK')
    pass
# 发布新闻
@profile_blue.route('/news_release',methods=['GET','POST'])
@login_required
def news_release():
    user=g.user
    if request.method=='GET':
        try:
            categorys=Category.query.all()
            # categorys=Category.query.filter(Category.id!=1).all()

        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='读取数据库失败')
        if not categorys:
            return jsonify(errno=RET.NODATA,errmsg='没有新闻排行数据')
        category_list=[]
        for category in categorys:
            category_list.append(category.to_dict())
        # category_list.remove(category_list[0])
        category_list.pop(0)
        return render_template('news/user_news_release.html',data={'category_list':category_list})
    title=request.form.get('title')
    category_id=request.form.get('category_id')
    digest=request.form.get('digest')
    index_image=request.files.get('index_image')
    content=request.form.get('content')
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        img=index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='读取标题图片数据失败')
    try:
        img_url=storage(img)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='上传图片到七牛云失败')
    news=News()
    news.title=title
    news.category_id=category_id
    news.digest=digest
    news.index_image=QINIU_DOMIN_PREFIX+img_url
    news.content=content
    news.source='个人发布'
    news.user_id=user.id
    news.status=1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='提交发布的新闻到数据库失败')
    return jsonify(errno=RET.OK,errmsg='OK')
    pass
